{% extends "base.html" %}

{% block title %}预约管理{% endblock %}

{% block extra_css %}
<style>
    .admin-header {
        background: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
        color: white;
        padding: 2rem 0;
        border-radius: 0 0 1rem 1rem;
        margin-bottom: 2rem;
    }

    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        margin-bottom: 2rem;
    }

    .stat-card {
        background: white;
        border-radius: 0.75rem;
        padding: 1.5rem;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        text-align: center;
        transition: transform 0.3s ease;
    }

    .stat-card:hover {
        transform: translateY(-2px);
    }

    .stat-icon {
        width: 60px;
        height: 60px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 1rem;
        font-size: 1.5rem;
    }

    .stat-number {
        font-size: 2rem;
        font-weight: bold;
        color: #2c3e50;
        margin-bottom: 0.5rem;
    }

    .stat-label {
        color: #6c757d;
        font-size: 0.875rem;
    }

    .filters-section {
        background: white;
        border-radius: 0.75rem;
        padding: 1.5rem;
        margin-bottom: 2rem;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }

    .filters-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        margin-bottom: 1rem;
    }

    /* 简化的现代表格样式 */
    .reservations-table {
        background: white;
        border-radius: 12px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
        overflow: hidden;
        border: 1px solid #e8ecef;
    }

    .table-header {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border-bottom: 2px solid #dee2e6;
        padding: 1.25rem 1.5rem;
        display: flex;
        justify-content: between;
        align-items: center;
    }

    .table-header h5 {
        margin: 0;
        color: #495057;
        font-weight: 600;
    }

    /* 简化表格样式 */
    .simple-table {
        width: 100%;
        margin: 0;
    }

    .simple-table th {
        background: #f8f9fa;
        border: none;
        color: #6c757d;
        font-weight: 500;
        font-size: 0.875rem;
        padding: 1rem 1.25rem;
        text-transform: uppercase;
        letter-spacing: 0.025em;
        border-bottom: 1px solid #dee2e6;
    }

    .simple-table td {
        border: none;
        padding: 1.25rem 1.25rem;
        vertical-align: middle;
        border-bottom: 1px solid #f8f9fa;
        font-size: 0.9rem;
    }

    .simple-table tbody tr {
        transition: all 0.2s ease;
    }

    .simple-table tbody tr:hover {
        background-color: #f8f9fa;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .simple-table tbody tr:last-child td {
        border-bottom: none;
    }

    /* 状态标签简化 */
    .status-badge {
        display: inline-flex;
        align-items: center;
        padding: 0.25rem 0.75rem;
        border-radius: 50px;
        font-size: 0.75rem;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }

    .status-pending { background: #fff3cd; color: #856404; }
    .status-confirmed { background: #d1ecf1; color: #0c5460; }
    .status-completed { background: #d4edda; color: #155724; }
    .status-cancelled { background: #f8d7da; color: #721c24; }

    /* 简化的操作按钮 */
    .action-group {
        display: flex;
        gap: 0.5rem;
        align-items: center;
    }

    .btn-simple {
        padding: 0.375rem 0.75rem;
        font-size: 0.8rem;
        border-radius: 6px;
        border: 1px solid #dee2e6;
        background: white;
        color: #6c757d;
        transition: all 0.2s ease;
        text-decoration: none;
    }

    .btn-simple:hover {
        background: #f8f9fa;
        border-color: #adb5bd;
        color: #495057;
        transform: translateY(-1px);
    }

    .btn-simple.btn-primary { background: #007bff; color: white; border-color: #007bff; }
    .btn-simple.btn-success { background: #28a745; color: white; border-color: #28a745; }
    .btn-simple.btn-danger { background: #dc3545; color: white; border-color: #dc3545; }

    .btn-simple.btn-primary:hover { background: #0056b3; }
    .btn-simple.btn-success:hover { background: #1e7e34; }
    .btn-simple.btn-danger:hover { background: #c82333; }

    /* 简化的用户信息显示 */
    .user-name {
        font-weight: 500;
        color: #495057;
        margin-bottom: 0.25rem;
    }

    .user-phone {
        color: #6c757d;
        font-size: 0.8rem;
    }

    /* 时间信息简化 */
    .time-display {
        font-weight: 500;
        color: #495057;
    }

    .date-display {
        color: #6c757d;
        font-size: 0.85rem;
    }

    /* 价格显示 */
    .price-display {
        font-weight: 600;
        color: #28a745;
        font-size: 1rem;
    }

    /* 复选框样式 */
    .form-check-input {
        margin-top: 0;
    }

    /* 批量操作栏简化 */
    .bulk-actions {
        background: #e3f2fd;
        border: 1px solid #bbdefb;
        border-radius: 8px;
        padding: 0.75rem 1rem;
        margin-bottom: 1rem;
        display: none;
    }

    .bulk-actions.show {
        display: flex;
        align-items: center;
        gap: 1rem;
    }

    .selected-count {
        font-weight: 500;
        color: #1976d2;
    }
    }


    /* 响应式设计优化 */
    @media (max-width: 1200px) {
        .simple-table th:nth-child(3),
        .simple-table td:nth-child(3) { display: none; } /* 隐藏教练列 */
        .simple-table th:nth-child(6),
        .simple-table td:nth-child(6) { display: none; } /* 隐藏球台列 */
    }

    @media (max-width: 992px) {
        .reservations-table {
            border-radius: 8px;
        }

        .simple-table th,
        .simple-table td {
            padding: 0.75rem 0.5rem;
            font-size: 0.875rem;
        }

        .action-group {
            flex-direction: column;
            gap: 0.25rem;
        }

        .btn-simple {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
        }
    }

    @media (max-width: 768px) {
        .simple-table th:nth-child(4),
        .simple-table td:nth-child(4) { display: none; } /* 隐藏时间安排列 */
        .simple-table th:nth-child(8),
        .simple-table td:nth-child(8) { display: none; } /* 隐藏费用列 */

        .simple-table th,
        .simple-table td {
            padding: 0.5rem 0.25rem;
            font-size: 0.8rem;
        }

        .reservations-table {
            margin: 0 -15px;
            border-radius: 0;
        }
    }

    @media (max-width: 576px) {
        .simple-table {
            font-size: 0.75rem;
        }

        .action-group {
            flex-direction: row;
            flex-wrap: wrap;
            gap: 0.125rem;
        }

        .btn-simple {
            font-size: 0.7rem;
            padding: 0.125rem 0.375rem;
        }

        .status-badge {
            font-size: 0.65rem;
            padding: 0.125rem 0.5rem;
        }
    }


    .bulk-actions {
        background: #e3f2fd;
        border-radius: 0.5rem;
        padding: 1rem;
        margin-bottom: 1rem;
        display: none;
    }

    .bulk-actions.active {
        display: block;
    }


    .time-info {
        font-size: 0.875rem;
        color: #6c757d;
    }

    @media (max-width: 768px) {
        .admin-header {
            padding: 1rem 0;
        }

        .filters-grid {
            grid-template-columns: 1fr;
        }

        .table-responsive {
            font-size: 0.875rem;
        }

        .action-buttons {
            flex-direction: row;
            gap: 0.125rem;
            min-width: auto;
        }

        .action-buttons .btn {
            min-width: 28px;
            height: 28px;
            padding: 0.125rem 0.25rem;
        }

        .student-info,
        .coach-info {
            flex-direction: column;
            align-items: flex-start;
        }

        .student-avatar,
        .coach-avatar {
            margin-bottom: 0.25rem;
            margin-right: 0;
        }

        /* 确保操作列有足够宽度 */
        .table td:last-child {
            min-width: 250px;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="admin-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h1 class="mb-0">
                    <i class="fas fa-calendar-check me-2"></i>预约管理
                </h1>
                <p class="mb-0 mt-2 opacity-75">全面监管系统中的所有预约</p>
            </div>
            <div class="col-md-4 text-end">
                <div class="btn-group">
                    <a href="{{ url_for('admin_reservations.statistics') }}" class="btn btn-light">
                        <i class="fas fa-chart-bar me-1"></i>统计分析
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid">
    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-calendar-alt"></i>
            </div>
            <div class="stat-number">{{ stats.total_count }}</div>
            <div class="stat-label">总预约数</div>
        </div>

        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-clock"></i>
            </div>
            <div class="stat-number">{{ stats.today_count }}</div>
            <div class="stat-label">今日预约</div>
        </div>

        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-hourglass-half"></i>
            </div>
            <div class="stat-number">{{ stats.pending_count }}</div>
            <div class="stat-label">待处理</div>
        </div>

        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-number">{{ stats.total_reservations }}</div>
            <div class="stat-label">总预约数</div>
        </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filters-section">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h5 class="mb-0">筛选条件</h5>
        </div>

        <form method="GET" action="{{ url_for('admin_reservations.list_reservations') }}" id="filterForm">
            <div class="filters-grid">
                <div>
                    <label class="form-label">状态</label>
                    <select class="form-select" name="status">
                        <option value="">所有状态</option>
                        <option value="pending" {% if current_filters.status == 'pending' %}selected{% endif %}>待处理</option>
                        <option value="confirmed" {% if current_filters.status == 'confirmed' %}selected{% endif %}>已确认</option>
                        <option value="completed" {% if current_filters.status == 'completed' %}selected{% endif %}>已完成</option>
                        <option value="cancelled" {% if current_filters.status == 'cancelled' %}selected{% endif %}>已取消</option>
                        <option value="no_show" {% if current_filters.status == 'no_show' %}selected{% endif %}>未到场</option>
                    </select>
                </div>

                <div>
                    <label class="form-label">校区</label>
                    <select class="form-select" name="campus_id"
                            {% if current_user.role == 'campus_admin' %}disabled{% endif %}>
                        {% if current_user.role == 'super_admin' %}
                        <option value="">所有校区</option>
                        {% endif %}
                        {% for campus in campuses %}
                        <option value="{{ campus.id }}" {% if current_filters.campus_id == campus.id %}selected{% endif %}>
                            {{ campus.name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>

                <div>
                    <label class="form-label">教练</label>
                    <select class="form-select" name="coach_id">
                        <option value="">所有教练</option>
                        {% for coach in coaches %}
                        <option value="{{ coach.id }}" {% if current_filters.coach_id == coach.id %}selected{% endif %}>
                            {{ coach.real_name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>

                <div>
                    <label class="form-label">开始日期</label>
                    <input type="date" class="form-control" name="start_date" value="{{ current_filters.start_date or '' }}">
                </div>

                <div>
                    <label class="form-label">结束日期</label>
                    <input type="date" class="form-control" name="end_date" value="{{ current_filters.end_date or '' }}">
                </div>

                <div>
                    <label class="form-label">搜索</label>
                    <input type="text" class="form-control" name="search"
                           placeholder="学员姓名、电话、备注..."
                           value="{{ current_filters.search or '' }}">
                </div>
            </div>

            <div class="d-flex justify-content-between align-items-center mt-3">
                <div class="btn-group">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search me-1"></i>搜索
                    </button>
                    <a href="{{ url_for('admin_reservations.list_reservations') }}" class="btn btn-outline-secondary">
                        <i class="fas fa-undo me-1"></i>重置
                    </a>
                </div>

                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                    <label class="form-check-label" for="selectAll">
                        全选
                    </label>
                </div>
            </div>
        </form>
    </div>

    <!-- 批量操作区域 -->
    <div class="bulk-actions" id="bulkActions">
        <div class="d-flex justify-content-between align-items-center">
            <span>已选择 <span id="selectedCount">0</span> 个预约</span>
            <div class="btn-group">
                <button type="button" class="btn btn-success btn-sm" onclick="bulkAction('confirm')">
                    <i class="fas fa-check me-1"></i>批量确认
                </button>
                <button type="button" class="btn btn-warning btn-sm" onclick="bulkAction('cancel')">
                    <i class="fas fa-times me-1"></i>批量取消
                </button>
                <button type="button" class="btn btn-danger btn-sm" onclick="bulkAction('delete')">
                    <i class="fas fa-trash me-1"></i>批量删除
                </button>
            </div>
        </div>
    </div>

    <!-- 预约列表 -->
    <div class="reservations-table">
        <div class="table-header">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="mb-0">预约列表</h5>
                <small class="text-muted">
                    共 {{ reservations.total }} 条记录，第 {{ reservations.page }} 页
                </small>
            </div>
        </div>

        <div class="reservations-table">
            <table class="simple-table">
                <thead>
                    <tr>
                        <th width="50">
                            <input type="checkbox" id="selectAllTable" onchange="toggleSelectAll()">
                        </th>
                        <th>预约信息</th>
                        <th>学员</th>
                        <th>教练</th>
                        <th>时间安排</th>
                        <th>球台</th>
                        <th>状态</th>
                        <th>费用</th>
                        <th width="280">操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for reservation in reservations.items %}
                    <tr class="{% if reservation.is_urgent %}priority-medium{% endif %}">
                        <td>
                            <input type="checkbox" class="reservation-checkbox" value="{{ reservation.id }}">
                        </td>
                        <td>
                            <div>
                                <strong>#{{ reservation.id }}</strong>
                            </div>
                            <small class="text-muted">
                                {{ reservation.created_at.strftime('%m/%d %H:%M') }}
                            </small>
                        </td>
                        <td>
                            <div>{{ reservation.student.real_name }}</div>
                            <small class="text-muted">{{ reservation.student.phone }}</small>
                        </td>
                        <td>
                            <div>{{ reservation.coach.real_name }}</div>
                            <small class="text-muted">{{ reservation.coach.phone }}</small>
                        </td>
                        <td>
                            <div>{{ reservation.reservation_date.strftime('%m/%d') }}</div>
                            <div class="time-info">
                                {{ reservation.start_time.strftime('%H:%M') }}-{{ reservation.end_time.strftime('%H:%M') }}
                            </div>
                            <small class="text-muted">({{ reservation.duration_minutes }}分钟)</small>
                        </td>
                        <td>
                            <div>{{ reservation.table.name }}</div>
                            <small class="text-muted">{{ reservation.table.campus.name }}</small>
                        </td>
                        <td>
                            <span class="status-badge status-{{ reservation.status }}">
                                {{ reservation.status_text }}
                            </span>
                        </td>
                        <td>
                            {% if reservation.price %}
                            <span class="text-success">¥{{ reservation.price }}</span>
                            {% else %}
                            <span class="text-muted">未设置</span>
                            {% endif %}
                        </td>
                        <td>
                            <div class="action-group">
                                <a href="{{ url_for('admin_reservations.detail', reservation_id=reservation.id) }}"
                                   class="btn-simple">查看</a>

                                {% if reservation.status == 'pending' %}
                                <button type="button" class="btn-simple"
                                        onclick="forceConfirm({{ reservation.id }})">确认</button>
                                {% endif %}

                                {% if reservation.status not in ['cancelled', 'completed'] %}
                                <button type="button" class="btn-simple"
                                        onclick="forceCancel({{ reservation.id }})">取消</button>
                                {% endif %}

                                <button type="button" class="btn-simple"
                                        onclick="editReservation({{ reservation.id }})">编辑</button>
                                <button type="button" class="btn-simple"
                                        onclick="deleteReservation({{ reservation.id }})">删除</button>
                            </div>
                        </td>
                    </tr>
                    {% else %}
                    <tr>
                        <td colspan="9" class="text-center py-4">
                            <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                            <p class="text-muted">暂无预约记录</p>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>

        <!-- 分页 -->
        {% if reservations.total > 0 %}
        <div class="d-flex justify-content-between align-items-center p-3">
            <div>
                <small class="text-muted">
                    显示第 {{ (reservations.page - 1) * reservations.per_page + 1 }} 到
                    {{ reservations.page * reservations.per_page if reservations.page * reservations.per_page < reservations.total else reservations.total }} 条，
                    共 {{ reservations.total }} 条记录
                </small>
            </div>

            {% if reservations.pages > 1 %}
            <nav>
                <ul class="pagination pagination-sm mb-0">
                    {% if reservations.has_prev %}
                    <li class="page-item">
                        <a class="page-link" href="{{ url_for('admin_reservations.list_reservations', page=reservations.prev_num, **current_filters) }}">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    </li>
                    {% endif %}

                    {% for page_num in reservations.iter_pages() %}
                        {% if page_num %}
                            {% if page_num != reservations.page %}
                            <li class="page-item">
                                <a class="page-link" href="{{ url_for('admin_reservations.list_reservations', page=page_num, **current_filters) }}">
                                    {{ page_num }}
                                </a>
                            </li>
                            {% else %}
                            <li class="page-item active">
                                <span class="page-link">{{ page_num }}</span>
                            </li>
                            {% endif %}
                        {% else %}
                        <li class="page-item disabled">
                            <span class="page-link">…</span>
                        </li>
                        {% endif %}
                    {% endfor %}

                    {% if reservations.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="{{ url_for('admin_reservations.list_reservations', page=reservations.next_num, **current_filters) }}">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                    {% endif %}
                </ul>
            </nav>
            {% endif %}
        </div>
        {% endif %}
    </div>
</div>

<!-- 强制取消确认模态框 -->
<div class="modal fade" id="forceCancelModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">强制取消预约</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>警告：</strong>这是管理员强制操作，将直接取消预约，请谨慎操作。
                </div>
                <div class="mb-3">
                    <label class="form-label">取消原因</label>
                    <textarea class="form-control" id="forceCancelReason" rows="3"
                              placeholder="请输入取消原因..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmForceCancel()">确认取消</button>
            </div>
        </div>
    </div>
</div>

<!-- 批量操作确认模态框 -->
<div class="modal fade" id="bulkActionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="bulkActionTitle">批量操作确认</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="bulkActionContent"></div>
                <div class="mb-3" id="bulkReasonSection" style="display: none;">
                    <label class="form-label">操作原因</label>
                    <textarea class="form-control" id="bulkActionReason" rows="3"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmBulkAction">确认操作</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let selectedReservations = [];
let currentForceCancelId = null;
let currentBulkAction = null;

$(document).ready(function() {
    // 监听复选框变化
    $('.reservation-checkbox').change(function() {
        updateSelectedReservations();
    });
});

// 切换全选
function toggleSelectAll() {
    const selectAll = $('#selectAll').is(':checked') || $('#selectAllTable').is(':checked');
    $('.reservation-checkbox').prop('checked', selectAll);
    $('#selectAll').prop('checked', selectAll);
    $('#selectAllTable').prop('checked', selectAll);
    updateSelectedReservations();
}

// 更新选中的预约
function updateSelectedReservations() {
    selectedReservations = [];
    $('.reservation-checkbox:checked').each(function() {
        selectedReservations.push(parseInt($(this).val()));
    });

    $('#selectedCount').text(selectedReservations.length);

    if (selectedReservations.length > 0) {
        $('#bulkActions').addClass('active');
    } else {
        $('#bulkActions').removeClass('active');
    }

    // 更新全选状态
    const totalCheckboxes = $('.reservation-checkbox').length;
    const checkedCheckboxes = $('.reservation-checkbox:checked').length;

    $('#selectAll').prop('checked', checkedCheckboxes === totalCheckboxes);
    $('#selectAllTable').prop('checked', checkedCheckboxes === totalCheckboxes);
}

// 强制确认预约
function forceConfirm(reservationId) {
    if (!confirm('确定要强制确认这个预约吗？')) return;

    $.post(`{{ url_for('admin_reservations.api_force_confirm', reservation_id=0) }}`.replace('0', reservationId), function(response) {
        if (response.success) {
            showAlert('success', response.message);
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('error', response.message);
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 强制取消预约
function forceCancel(reservationId) {
    currentForceCancelId = reservationId;
    $('#forceCancelModal').modal('show');
}

function confirmForceCancel() {
    const reason = $('#forceCancelReason').val().trim();
    if (!reason) {
        showAlert('error', '请输入取消原因');
        return;
    }

    $.post(`{{ url_for('admin_reservations.api_force_cancel', reservation_id=0) }}`.replace('0', currentForceCancelId), {
        reason: reason
    }, function(response) {
        if (response.success) {
            showAlert('success', response.message);
            $('#forceCancelModal').modal('hide');
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('error', response.message);
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 批量操作
function bulkAction(action) {
    if (selectedReservations.length === 0) {
        showAlert('error', '请先选择要操作的预约');
        return;
    }

    currentBulkAction = action;
    let title = '';
    let content = '';
    let showReason = false;

    switch (action) {
        case 'confirm':
            title = '批量确认预约';
            content = `确定要确认选中的 ${selectedReservations.length} 个预约吗？`;
            break;
        case 'cancel':
            title = '批量取消预约';
            content = `确定要取消选中的 ${selectedReservations.length} 个预约吗？`;
            showReason = true;
            break;
        case 'delete':
            title = '批量删除预约';
            content = `<div class="alert alert-danger">
                <strong>警告：</strong>删除操作不可撤销！确定要删除选中的 ${selectedReservations.length} 个预约吗？
            </div>`;
            showReason = true;
            break;
    }

    $('#bulkActionTitle').text(title);
    $('#bulkActionContent').html(content);

    if (showReason) {
        $('#bulkReasonSection').show();
    } else {
        $('#bulkReasonSection').hide();
    }

    $('#bulkActionModal').modal('show');
}

// 确认批量操作
$('#confirmBulkAction').click(function() {
    const reason = $('#bulkActionReason').val();

    $.ajax({
        url: '{{ url_for("admin_reservations.api_bulk_action") }}',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            reservation_ids: selectedReservations,
            action: currentBulkAction,
            reason: reason
        }),
        success: function(response) {
            if (response.success) {
                showAlert('success', response.message);
                $('#bulkActionModal').modal('hide');
                setTimeout(() => location.reload(), 1500);
            } else {
                showAlert('error', response.message);
            }
        },
        error: function() {
            showAlert('error', '网络错误，请重试');
        }
    });
});


// 编辑预约
function editReservation(reservationId) {
    // 跳转到编辑页面
    window.location.href = `{{ url_for('admin_reservations.edit', reservation_id=0) }}`.replace('0', reservationId);
}

// 复制预约
function duplicateReservation(reservationId) {
    if (!confirm('确定要复制这个预约吗？将创建一个相同设置但时间为明天的新预约。')) return;

    $.post(`{{ url_for('admin_reservations.api_duplicate_reservation', reservation_id=0) }}`.replace('0', reservationId), function(response) {
        if (response.success) {
            showAlert('success', response.message);
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('error', response.message);
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 删除预约
function deleteReservation(reservationId) {
    if (!confirm('确定要删除这个预约吗？此操作不可撤销！')) return;

    $.post(`{{ url_for('admin_reservations.api_delete_reservation', reservation_id=0) }}`.replace('0', reservationId), function(response) {
        if (response.success) {
            showAlert('success', response.message);
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('error', response.message);
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 显示提示信息
function showAlert(type, message) {
    const alertClass = type === 'success' ? 'alert-success' :
                      type === 'info' ? 'alert-info' : 'alert-danger';
    const icon = type === 'success' ? 'check-circle' :
                 type === 'info' ? 'info-circle' : 'exclamation-triangle';

    const alert = $(`
        <div class="alert ${alertClass} alert-dismissible fade show position-fixed"
             style="top: 20px; right: 20px; z-index: 9999;">
            <i class="fas fa-${icon} me-2"></i>${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `);

    $('body').append(alert);

    setTimeout(function() {
        alert.alert('close');
    }, 3000);
}

</script>
{% endblock %}